package com.itheima.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;

/**
 * 密码加密工具类
 *
 * @author 黑马程序员
 * @Company http://www.itheima.com
 */
public class MD5Util {

    /**
     * 密码加密
     *
     * @param password
     * @return
     * @throws Exception
     */
    public static String md5(String password) {
        try {
            //1.创建加密对象
            MessageDigest md5 = MessageDigest.getInstance("md5");
            //2.加密密码
            byte[] by = md5.digest(password.getBytes());
            //3.创建编码对象
            BASE64Encoder encoder = new BASE64Encoder();
            //4.对结果编码
            return encoder.encode(by);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //盐的例子,后续需要修改
    public static String md5Salt(String password) {
        // 生成盐 指定盐的长度
        String salt = RandomStringUtils.randomAlphanumeric(8);
        //密码加密加盐
        String digestAsHex = DigestUtils.md5DigestAsHex(("123456" + salt).getBytes());
        // System.out.println("salt:" + salt + "---password:" + digestAsHex);
        return digestAsHex;
    }

    //sha256散列的处理思路,通过盐处理
    public static String sha256Salt() {
        // 创建BCryptPasswordEncoder对象
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 对密码进行加密
        String pass = bCryptPasswordEncoder.encode("admin");
        // 对密码进行验证
        boolean matches = bCryptPasswordEncoder.matches("admin", pass);
        // 输出加密结果及验证结果
        System.out.println(pass + "-----" + matches);
        return null;
    }
}
